#ifndef HEAD
#define HEAD
#include<iostream>
#define vertexnum 4
using namespace std;
void show( int **adj ){
    for ( int i = 0; i < vertexnum; i++)
        {
        for( int j = 0; j < vertexnum; j++)
            {
            if(adj[i][j]>=0)
                cout<<adj[i][j]<<"   ";
            else cout<<"*   ";
        }
        cout<<endl;
    }
}


class graph{
    public:
    int **adjgraph;//if there is an edge from i to j,then adjgraph[i][j]=1
    int *in;//in[i] stores the added up number of "comming in"edges of i; ****AT*A****
    int *mark;//if in[i]==0,then set mark[i]=1 and clear it out of the remaining vertices.
    graph();
    ~graph();
    void setEdge(int st,int en);
    void topo();
    int firstedge(int i);
    int nextedge(int i,int j);

};



void graph::topo(){
    cout<<endl<<endl<<"vertices:"<<endl;
    for(int i=0;i<vertexnum;i++)
        mark[i]=0;

    int flag;
    int counter=0;
    while(counter<vertexnum){
        flag=0;
        int i;
        for(i=0;i<vertexnum;i++){
            if(!mark[i]){
                flag=1;
                break;
            }
        }
        if(!flag&&i==vertexnum){
            cout<<"无环！"<<endl;
            break;
        }
        for(i=0;i<vertexnum;i++)
            in[i]=0;
        for(int i=0;i<vertexnum;i++)
            for(int j=0;j<vertexnum;j++){
                in[i]+=adjgraph[j][i];
//                cout<<endl<<in[i]<<endl;
            }
        for(int i=0;i<vertexnum;i++){
            if(!mark[i]&&!in[i])
            {
                for(int j=0;j<vertexnum;j++){
                    adjgraph[i][j]=0;
                }
                mark[i]=1;
                cout<<i<<"    ";
            }
        }
//        show(adjgraph);
//        cout<<endl;
        counter++;
    }

        cout<<endl<<endl<<"remaining vertices:    ";
        for(int i=0;i < vertexnum; i++){
            if(mark[i]==0){
                cout<<i<<"    ";
            }
        }
        cout<<endl;
}

void graph::setEdge(int st,int en){
    adjgraph[st][en]=1;
}
int graph::firstedge(int i){
    for(int j=0;j<vertexnum;j++)
        if ( adjgraph[i][j]>0 )
            return j;
    return -1;
}
int graph :: nextedge ( int i, int j) {
    for ( int k = j + 1; k < vertexnum; k++)
        if( adjgraph[i][j] > 0)
            return j;
    return -1;
}

graph::graph(){
    adjgraph = (int **) new int* [vertexnum];
    in = new int [vertexnum];
    mark = new int[vertexnum];
    for(int i=0; i < vertexnum; i++){
        adjgraph[i] = new int [vertexnum];
        in[i] = 0;
        for( int j=0; j < vertexnum; j++)
        {
            adjgraph[i][j]=0;
            }
    }
}

graph::~graph(){
    for(int i = 0 ; i < vertexnum; i++)
        delete adjgraph[i];
    delete adjgraph;
    delete in;
    delete mark;
}



#endif // HEAD

